import axios from 'axios'
import { MessageBox } from 'element-ui'
import store from '../store'
import qs from 'qs'
// import Cookies from 'js-cookie'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000, // 请求超时时间
  transformRequest: [function (data) {
    return qs.stringify(data)
  }]
})

// request拦截器
service.interceptors.request.use(config => {
  var token = store.getters.token
  if (token !== undefined && token !== '') {
    config.headers['Authorization'] = 'bearer ' + token // access_token 让每个请求携带自定义token 请根据实际情况自行修改
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  } else {
    config.headers['Authorization'] = 'Basic aHVhLWF1dGg6aHVhLWF1dGgtc2VjcmV0' // base64加密
  }
  return config
}, error => {
  // Do something with request error
  // console.log('这是request中的错误:' + error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错 可结合自己业务进行修改
     */
    const res = response.data
    var status = false
    if (res.status === 200) {
      status = true
    }
    if (response.status === 200) {
      status = true
    }
    if (!status) {
      return Promise.reject(res.status)
    } else {
      if (res.access_token) {
        // 存储token
        store.commit('SET_TOKEN', res.access_token)
      }
      return response.data
    }
  },
  error => {
    if (error.response.status === 401) {
      var msg = ''
      if (error.response.data.error === 'invalid_token') {
        msg = 'token已超时,请重新登录!'
      } else {
        msg = JSON.stringify(error.response.data)
      }
      MessageBox.confirm(msg, '确定登出', {
        confirmButtonText: '重新登录',
        // cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.commit('SET_TOKEN', '') // 清除token
        store.dispatch('FedLogOut').then(() => {
          location.reload()// 为了重新实例化vue-router对象 避免bug
        })
      })
    }
    return Promise.reject(error)
  }
)

export default service
